package com.zhangh.summer.admin.support.utils;

/**
 * @description: TODO
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-06-08 23:12
 **/

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;
import com.google.common.collect.Maps;

public class YmlUtil {

    private static Map<String, Object> ymlMap = null;

    static{
        ymlMap = Maps.newConcurrentMap();
        getApplicationYml();
    }

    /**
     *
     */
    public YmlUtil(){
        super();
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> getApplicationYml(){
        InputStream in=null;
        try {
            in=YmlUtil.class.getClassLoader().getResourceAsStream("bootstrap.yml");
            Yaml yaml = new Yaml();
            Map<String, Object> map = yaml.loadAs(in, Map.class);
            switchToMap(null, map);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null!=in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ymlMap;
    }

    @SuppressWarnings("unchecked")
    private static void switchToMap(String myKey,Map<String, Object> map){
        Iterator<String> it = map.keySet().iterator();
        myKey = myKey == null ? "" : myKey;
        String tmpkey = myKey;
        while(it.hasNext()){
            String key = it.next();
            myKey = tmpkey +key;
            Object value = map.get(key);
            if(value instanceof Map){
                switchToMap(myKey.concat("."), (Map<String, Object>)value);
            }else{
                if(null != value){
                    ymlMap.put(myKey, value);
                }
//                System.out.println(myKey+"->"+map.get(key));
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String key){
        return (T) ymlMap.get(key);
    }

    public static String getStr(String key){
        return String.valueOf(ymlMap.get(key));
    }

}
